// 核心应用结构和实现

use eframe::egui;
use html_parser::{aria::AriaManager, form::HtmlForm, DomNode, HtmlParser, ParserConfig};

use super::types::*;

// 扩展FeatureTester结构体，支持更多测试功能
pub struct FeatureTester {
    // 共享的HTML输入
    pub html_input: String,
    pub css_input: String,
    pub js_input: String,

    // 所选标签
    pub selected_tab: FeatureTab,
    pub selected_category: FeatureCategory,

    // HTML解析器相关字段
    pub parsed_result: Option<String>,
    pub parsed_result_display: String,
    pub css_selector: String,
    pub selector_results: String,
    pub validator_results: String,
    pub aria_info: String,
    pub form_info: String,
    pub dom_tree_info: String,
    pub links_info: String,
    pub cleaned_html: String,

    // SVG与MathML相关字段
    pub svg_input: String,
    pub svg_result: String,
    pub mathml_input: String,
    pub mathml_result: String,

    // HTML清理选项
    pub remove_scripts: bool,
    pub remove_styles: bool,
    pub remove_comments: bool,
    pub remove_attributes: bool,

    // CSS解析器相关字段
    pub css_parse_result: String,
    pub css_computed_styles: String,
    pub media_query_result: String,

    // 布局引擎相关字段
    pub layout_result: String,
    pub box_model_info: String,

    // 渲染引擎相关字段
    pub rendering_preview: String,

    // 网络相关字段
    pub http_url: String,
    pub http_method: HttpMethod,
    pub http_headers: String,
    pub http_response: String,
    pub http_request_body: String,
    pub http_content_type: String,

    // Cookie相关字段
    pub cookie_domain: String,
    pub cookie_list: Vec<CookieData>,
    pub new_cookie_name: String,
    pub new_cookie_value: String,
    pub new_cookie_path: String,
    pub new_cookie_secure: bool,
    pub new_cookie_http_only: bool,
    pub new_cookie_expiry: String,

    // JS相关字段
    pub js_execution_result: String,

    // 组件实例
    pub parser: HtmlParser,
    pub aria_manager: AriaManager,

    // CSS解析器相关新增字段
    pub viewport_width: f32,
    pub viewport_height: f32,
    pub pixel_ratio: f32,
    pub color_scheme: String,
    pub is_print_mode: bool,
    pub prefers_reduced_motion: bool,
    pub animation_progress: f32,
    pub is_animation_playing: bool,
    pub animation_info: String,

    // JavaScript相关新增字段
    pub js_execution_in_dom: bool,
    pub js_allow_network: bool,
    pub js_console_log: bool,
    pub js_strict_mode: bool,
    pub js_execution_timeout: u32,
    pub js_console_output: Vec<JsLog>,

    // DOM事件相关字段
    pub event_target_selector: String,
    pub selected_event_type: String,
    pub event_key_code: String,
    pub event_test_result: String,

    // UI组件相关字段
    pub ui_demo_text: String,
    pub ui_demo_multiline_text: String,
    pub ui_demo_checkbox: bool,
    pub ui_demo_radio: i32,
    pub ui_demo_slider: i32,
    pub ui_demo_combo_selected: String,
    pub ui_demo_tab: usize,
    pub ui_demo_color: [f32; 3],
    pub ui_demo_output: String,

    // 布局引擎相关新增字段
    pub flex_direction: String,
    pub justify_content: String,
    pub align_items: String,
    pub flex_wrap: String,
    pub grid_template_columns: String,
    pub grid_template_rows: String,
    pub grid_column_gap: i32,
    pub grid_row_gap: i32,
    pub grid_justify_content: String,
    pub grid_align_items: String,
    pub position_type: String,
    pub position_top: i32,
    pub position_left: i32,
    pub z_index: i32,
    pub use_transform: bool,
    pub transform_rotate: i32,
    pub transform_scale: f32,
}

impl eframe::App for FeatureTester {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        egui::CentralPanel::default().show(ctx, |ui| {
            // 标题
            ui.heading("RustBrowser 功能测试器");

            // 显示分类标签
            ui.horizontal(|ui| {
                if ui
                    .selectable_label(
                        self.selected_category == FeatureCategory::HtmlParser,
                        "HTML解析器",
                    )
                    .clicked()
                {
                    self.selected_category = FeatureCategory::HtmlParser;
                    self.selected_tab = FeatureTab::HtmlParser;
                }
                if ui
                    .selectable_label(
                        self.selected_category == FeatureCategory::CssParser,
                        "CSS解析器",
                    )
                    .clicked()
                {
                    self.selected_category = FeatureCategory::CssParser;
                    self.selected_tab = FeatureTab::CssParser;
                }
                if ui
                    .selectable_label(
                        self.selected_category == FeatureCategory::LayoutEngine,
                        "布局引擎",
                    )
                    .clicked()
                {
                    self.selected_category = FeatureCategory::LayoutEngine;
                    self.selected_tab = FeatureTab::BoxModel;
                }
                if ui
                    .selectable_label(
                        self.selected_category == FeatureCategory::RenderingEngine,
                        "渲染引擎",
                    )
                    .clicked()
                {
                    self.selected_category = FeatureCategory::RenderingEngine;
                    self.selected_tab = FeatureTab::Rendering;
                }
                if ui
                    .selectable_label(
                        self.selected_category == FeatureCategory::Network,
                        "网络模块",
                    )
                    .clicked()
                {
                    self.selected_category = FeatureCategory::Network;
                    self.selected_tab = FeatureTab::HttpClient;
                }
                if ui
                    .selectable_label(
                        self.selected_category == FeatureCategory::JavaScript,
                        "JavaScript",
                    )
                    .clicked()
                {
                    self.selected_category = FeatureCategory::JavaScript;
                    self.selected_tab = FeatureTab::JsInteraction;
                }
                if ui
                    .selectable_label(
                        self.selected_category == FeatureCategory::UserInterface,
                        "用户界面",
                    )
                    .clicked()
                {
                    self.selected_category = FeatureCategory::UserInterface;
                    self.selected_tab = FeatureTab::UiComponents;
                }
            });

            ui.separator();

            // 显示子标签
            self.render_subcategory_tabs(ui);

            ui.separator();

            // 根据所选标签渲染相应内容
            match self.selected_tab {
                // html_tabs-->html_tabs.rs HTML解析器相关功能
                FeatureTab::HtmlParser => self.render_html_parser_tab(ui),
                FeatureTab::DomManipulation => self.render_dom_manipulation_tab(ui),
                FeatureTab::CssSelector => self.render_css_selector_tab(ui),
                FeatureTab::Validation => self.render_validation_tab(ui),
                FeatureTab::HtmlSerialization => self.render_html_serialization_tab(ui),
                FeatureTab::FormProcessing => self.render_forms_tab(ui),
                FeatureTab::AriaSupport => self.render_aria_tab(ui),
                FeatureTab::DomTraversal => self.render_dom_traversal_tab(ui),
                FeatureTab::LinkExtractor => self.render_link_extractor_tab(ui),
                FeatureTab::HtmlCleaner => self.render_html_cleaner_tab(ui),
                FeatureTab::SvgSupport => self.render_svg_support_tab(ui),
                FeatureTab::MathMLSupport => self.render_mathml_support_tab(ui),

                // css_tabs-->css_tabs.rs CSS解析器相关功能
                FeatureTab::CssParser => self.render_css_parser_tab(ui),
                FeatureTab::SelectorParser => self.render_selector_parser_tab(ui),
                FeatureTab::StyleComputation => self.render_style_computation_tab(ui),
                FeatureTab::MediaQuery => self.render_media_query_tab(ui),
                FeatureTab::CssAnimation => self.render_css_animation_tab(ui),

                // layout_tabs-->layout_tabs.rs 布局引擎相关功能
                FeatureTab::BoxModel => self.render_box_model_tab(ui),
                FeatureTab::FlexLayout => self.render_flex_layout_tab(ui),
                FeatureTab::GridLayout => self.render_grid_layout_tab(ui),
                FeatureTab::Positioning => self.render_positioning_tab(ui),

                // render_tabs--> Render_tabs.rs 渲染引擎相关功能
                FeatureTab::Rendering => self.render_rendering_tab(ui),
                FeatureTab::TextRendering => self.render_text_rendering_tab(ui),
                FeatureTab::ImageRendering => self.render_image_rendering_tab(ui),

                // network_tabs-->network_tabs.rs 网络模块相关功能
                FeatureTab::HttpClient => self.render_http_client_tab(ui),
                FeatureTab::CookieManager => self.render_cookie_manager_tab(ui),

                // javascript_tabs-->javascript_tabs.rs JavaScript相关功能
                FeatureTab::JsInteraction => self.render_js_interaction_tab(ui),
                FeatureTab::DomEvents => self.render_dom_events_tab(ui),

                // ui_tabs-->ui_tabs.rs 用户界面相关功能
                FeatureTab::UiComponents => self.render_ui_components_tab(ui),
            }
        });
    }
}

impl FeatureTester {
    pub fn new() -> Self {
        let parser = HtmlParser::new(ParserConfig::default());
        let aria_manager = AriaManager::new();

        let mut feature_tester = Self {
            html_input: r#"<div class="container">
    <h1>测试HTML</h1>
    <p>这是一个<strong>测试</strong>段落。</p>
    <img src="test.jpg" alt="测试图片" />
</div>"#
                .to_string(),
            css_input: r#"
.container {
    max-width: 800px;
    margin: 0 auto;
    font-family: Arial, sans-serif;
}

h1 {
    color: #333;
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
}

p {
    line-height: 1.6;
    color: #666;
}

strong {
    color: #000;
    font-weight: bold;
}

img {
    max-width: 100%;
    height: auto;
    display: block;
    margin: 15px 0;
    border: 1px solid #ddd;
}
"#
            .to_string(),
            js_input: r#"
document.addEventListener('DOMContentLoaded', function() {
    const heading = document.querySelector('h1');
    if (heading) {
        heading.textContent += ' - 已加载';
        heading.style.color = '#007bff';
    }
    
    const img = document.querySelector('img');
    if (img) {
        img.addEventListener('click', function() {
            alert('图片被点击了！');
        });
    }
});
"#
            .to_string(),
            selected_tab: FeatureTab::HtmlParser,
            selected_category: FeatureCategory::HtmlParser,
            parsed_result: None,
            parsed_result_display: "点击'解析'按钮查看结果".to_string(),
            css_selector: "div h1".to_string(),
            selector_results: String::new(),
            validator_results: String::new(),
            aria_info: String::new(),
            form_info: String::new(),
            dom_tree_info: "点击'遍历DOM树'按钮查看结果".to_string(),
            links_info: "点击'提取链接'按钮查看结果".to_string(),
            cleaned_html: "点击'清理HTML'按钮查看结果".to_string(),
            remove_scripts: true,
            remove_styles: false,
            remove_comments: true,
            remove_attributes: false,
            css_parse_result: String::new(),
            css_computed_styles: String::new(),
            media_query_result: String::new(),
            layout_result: String::new(),
            box_model_info: String::new(),
            rendering_preview: String::new(),
            http_url: "https://example.com".to_string(),
            http_method: HttpMethod::Get,
            http_headers: "User-Agent: RustBrowser/0.1\nAccept: text/html".to_string(),
            http_response: String::new(),
            http_request_body: String::new(),
            http_content_type: "application/json".to_string(),
            cookie_domain: "example.com".to_string(),
            cookie_list: Vec::new(),
            new_cookie_name: String::new(),
            new_cookie_value: String::new(),
            new_cookie_path: "/".to_string(),
            new_cookie_secure: false,
            new_cookie_http_only: false,
            new_cookie_expiry: "会话结束".to_string(),
            js_execution_result: String::new(),
            parser,
            aria_manager,
            svg_input: r#"<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
    <circle cx="100" cy="100" r="80" fill="blue" />
    <rect x="60" y="60" width="80" height="80" fill="red" />
    <text x="100" y="150" text-anchor="middle" fill="white">SVG测试</text>
</svg>"#
                .to_string(),
            svg_result: String::new(),
            mathml_input: r#"<math xmlns="http://www.w3.org/1998/Math/MathML">
    <mrow>
        <mi>x</mi>
        <mo>+</mo>
        <mfrac>
            <mn>1</mn>
            <mn>2</mn>
        </mfrac>
        <mo>=</mo>
        <mn>5</mn>
    </mrow>
</math>"#
                .to_string(),
            mathml_result: String::new(),

            // 初始化CSS解析器相关字段
            viewport_width: 1024.0,
            viewport_height: 768.0,
            pixel_ratio: 1.0,
            color_scheme: "light".to_string(),
            is_print_mode: false,
            prefers_reduced_motion: false,
            animation_progress: 0.0,
            is_animation_playing: false,
            animation_info: String::new(),

            // JavaScript相关字段初始化
            js_execution_in_dom: true,
            js_allow_network: false,
            js_console_log: true,
            js_strict_mode: false,
            js_execution_timeout: 5000,
            js_console_output: Vec::new(),

            // DOM事件相关字段初始化
            event_target_selector: "img".to_string(),
            selected_event_type: "click".to_string(),
            event_key_code: "Enter".to_string(),
            event_test_result: String::new(),

            // UI组件相关字段初始化
            ui_demo_text: "示例文本".to_string(),
            ui_demo_multiline_text: "这是多行文本输入框。\n您可以输入多行内容。".to_string(),
            ui_demo_checkbox: false,
            ui_demo_radio: 0,
            ui_demo_slider: 50,
            ui_demo_combo_selected: "选项1".to_string(),
            ui_demo_tab: 0,
            ui_demo_color: [0.3, 0.5, 0.8],
            ui_demo_output: String::new(),

            // 布局引擎相关字段初始化
            flex_direction: "row".to_string(),
            justify_content: "flex-start".to_string(),
            align_items: "stretch".to_string(),
            flex_wrap: "nowrap".to_string(),
            grid_template_columns: "repeat(3, 1fr)".to_string(),
            grid_template_rows: "repeat(3, 1fr)".to_string(),
            grid_column_gap: 10,
            grid_row_gap: 10,
            grid_justify_content: "start".to_string(),
            grid_align_items: "stretch".to_string(),
            position_type: "static".to_string(),
            position_top: 0,
            position_left: 0,
            z_index: 1,
            use_transform: false,
            transform_rotate: 0,
            transform_scale: 1.0,
        };

        feature_tester
    }

    // 渲染子分类标签
    pub fn render_subcategory_tabs(&mut self, ui: &mut egui::Ui) {
        ui.horizontal_wrapped(|ui| match self.selected_category {
            FeatureCategory::HtmlParser => {
                self.selectable_tab(ui, FeatureTab::HtmlParser, "HTML解析");
                self.selectable_tab(ui, FeatureTab::DomManipulation, "DOM操作");
                self.selectable_tab(ui, FeatureTab::CssSelector, "CSS选择器");
                self.selectable_tab(ui, FeatureTab::Validation, "HTML验证");
                self.selectable_tab(ui, FeatureTab::HtmlSerialization, "HTML序列化");
                self.selectable_tab(ui, FeatureTab::FormProcessing, "表单处理");
                self.selectable_tab(ui, FeatureTab::AriaSupport, "ARIA支持");
                self.selectable_tab(ui, FeatureTab::DomTraversal, "DOM遍历");
                self.selectable_tab(ui, FeatureTab::LinkExtractor, "链接提取");
                self.selectable_tab(ui, FeatureTab::HtmlCleaner, "HTML清理");
                self.selectable_tab(ui, FeatureTab::SvgSupport, "SVG支持");
                self.selectable_tab(ui, FeatureTab::MathMLSupport, "MathML支持");
            }
            FeatureCategory::CssParser => {
                self.selectable_tab(ui, FeatureTab::CssParser, "CSS解析");
                self.selectable_tab(ui, FeatureTab::SelectorParser, "选择器解析");
                self.selectable_tab(ui, FeatureTab::StyleComputation, "样式计算");
                self.selectable_tab(ui, FeatureTab::MediaQuery, "媒体查询");
                self.selectable_tab(ui, FeatureTab::CssAnimation, "CSS动画");
            }
            FeatureCategory::LayoutEngine => {
                self.selectable_tab(ui, FeatureTab::BoxModel, "盒模型");
                self.selectable_tab(ui, FeatureTab::FlexLayout, "弹性布局");
                self.selectable_tab(ui, FeatureTab::GridLayout, "网格布局");
                self.selectable_tab(ui, FeatureTab::Positioning, "定位系统");
            }
            FeatureCategory::RenderingEngine => {
                self.selectable_tab(ui, FeatureTab::Rendering, "渲染测试");
                self.selectable_tab(ui, FeatureTab::TextRendering, "文本渲染");
                self.selectable_tab(ui, FeatureTab::ImageRendering, "图像渲染");
            }
            FeatureCategory::Network => {
                self.selectable_tab(ui, FeatureTab::HttpClient, "HTTP请求");
                self.selectable_tab(ui, FeatureTab::CookieManager, "Cookie管理");
            }
            FeatureCategory::JavaScript => {
                self.selectable_tab(ui, FeatureTab::JsInteraction, "JS交互");
                self.selectable_tab(ui, FeatureTab::DomEvents, "DOM事件");
            }
            FeatureCategory::UserInterface => {
                self.selectable_tab(ui, FeatureTab::UiComponents, "UI组件");
            }
        });
    }

    // 辅助方法：可选择标签
    pub fn selectable_tab(&mut self, ui: &mut egui::Ui, tab: FeatureTab, label: &str) {
        if ui
            .selectable_label(self.selected_tab == tab, label)
            .clicked()
        {
            self.selected_tab = tab.clone();
        }
    }
}

// 保留这个Default实现
impl Default for FeatureTester {
    fn default() -> Self {
        Self::new()
    }
}

// 声明静态变量用于存储各个测试标签页的结果
pub static mut DOM_TREE_INFO: String = String::new();
pub static mut LINKS_INFO: String = String::new();
pub static mut CLEANED_HTML: String = String::new();
